package com.base.dataStructure.stack;

import java.util.Iterator;

/**
 * @Author: hdhao
 * @Create: 2023/4/1 - 17:01
 * @Version: v1.0
 */
//基于链表实现栈结构
@SuppressWarnings("all")
public class LinkedListStack<E> implements Stack<E>,Iterable<E> {
    private int capacity;
    private int size;
    private Node<E> head = new Node<E>(null,null);

    @Override
    public boolean push(E value) {
        //判断栈是否已满,满了就无法添加
        if (isFull()){
            return false;
        }
        //创建新的节点,注意新节点的next指针应该指向谁
        Node<E> added = new Node<>(value, head.next);
        //添加到栈中
        head.next = added;
        //栈数量+1
        size++;
        return true;
    }

    @Override
    public E pop() {
        //当栈为空时,直接返回null
        if (isEmpty()){
            return null;
        }
        //栈里第一个节点是head.next
        Node<E> first = head.next;
        //删除第一个节点
        head.next = first.next;
        size--;
        return first.value;
    }

    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        //栈里第一个节点是head.next
        return head.next.value;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = head.next;
            @Override
            public boolean hasNext() {
                return p !=null;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    static class Node<E>{
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }
}
